import { defineStore } from 'pinia'
import { v4 as uuidv4 } from 'uuid';

// 面板项接口（保留原有 id，新增 panelId 作为前端唯一标识）
export interface PromptItem {
  id: string;
  panelId: string; // 前端唯一标识，用于关联配置
  type: string;
  name: string;
  customize_name: string;
  image: string;
  tags: string;
  rating: number;
  favorite: number;
  disliked: number;
  use: boolean; // 控制标签是否参与合并
}

// 配置接口（直接使用 panelId 与面板项绑定）
export interface RandomConfig {
  panelId: string; // 与 PromptItem.panelId 完全一致，无需额外 uuid
  class_type: string;
  value: [number, number];
  favorite: boolean | null;
  disliked: boolean | null;
  min_rating: number | null;
  max_rating: number | null;
}

interface Lora {
  lora_name: string;
  lora_image: string | null;
  strength_model: number;
  strength_clip: number;
  lora_config: string;
  lora_label: string;
  tags: string;
  parent_folder: string;
  grandparent_folder: string;
  isLoadingConfig: boolean;
}

const DEFAULT_TYPES = ['style','collect','cloth','action'];
const defaultTypePanelIds = DEFAULT_TYPES.map(type => ({
  type,
  panelId: uuidv4() // 每个类型对应唯一 panelId
}));

export const useExPrompt = defineStore('exPrompt', {
  state: () => ({
    character: {
      tags: '',
    },
    items: defaultTypePanelIds.map(({ type, panelId }) => ({
      id: '', // 原有 id 初始为空
      panelId, // 使用预生成的 panelId
      type,
      name: '',
      customize_name: '',
      image: '',
      tags: '',
      rating: 0,
      favorite: 0,
      disliked: 0,
      use: true,
    })) as PromptItem[],
    
    randomConfigs: defaultTypePanelIds.map(({ type, panelId }) => ({
      panelId, // 与 items 中的 panelId 完全一致
      class_type:type,
      value: [0, 0],
      favorite: null,
      disliked: null,
      min_rating: 0,
      max_rating: 0,
    })) as RandomConfig[],
    random: { tags: '' },
    ai: { tags: '' },
    loraList: [] as Lora[]
  }),
  getters: {
    loraListJson: (state) => JSON.stringify(state.loraList),
    getRandomConfigByPanelId: (state) => (panelId: string) => {
      return state.randomConfigs.find(config => config.panelId === panelId) || {
        panelId: '',
        class_type: '',
        value: [0, 0],
        favorite: null,
        disliked: null,
        min_rating: 0,
        max_rating: 0,
      };
    },
    
    // 根据类型获取面板项
    getItemsByType: (state) => (type: string) => {
      return state.items.filter(item => item.type === type);
    },
    
    // 获取所有唯一类型
    getUniqueTypes: (state) => [...new Set(state.items.map(item => item.type))],
    
    defaultTypes: () => [...DEFAULT_TYPES]
  },
  actions: {
    // 添加新面板实例（同时创建关联的配置）
    addNewItem(type: string) {
      const panelId = uuidv4(); // 生成新的 panelId
      
      // 添加面板项
      this.items.push({
        id: '', // 保留原有 id 字段
        panelId,
        type,
        name: '',
        customize_name: '',
        image: '',
        tags: '',
        rating: 0,
        favorite: 0,
        disliked: 0,
        use: true,
      });
      this.randomConfigs.push({
        panelId, 
        class_type:type,
        value: [0, 0],
        favorite: null,
        disliked: null,
        min_rating: 0,
        max_rating: 0,
      });
      
      return panelId;
    },
    removeItemByPanelId(panelId: string) {
      const itemToRemove = this.items.find(item => item.panelId === panelId);
      if (itemToRemove && DEFAULT_TYPES.includes(itemToRemove.type)) {
        // 确保默认类型至少保留一个实例
        const sameTypeItems = this.getItemsByType(itemToRemove.type);
        if (sameTypeItems.length <= 1) {
          return false;
        }
      }
      this.items = this.items.filter(item => item.panelId !== panelId);
      this.randomConfigs = this.randomConfigs.filter(config => config.panelId !== panelId);
      return true;
    },
    
    // 根据 panelId 更新面板项
    updateItemByPanelId(item: Partial<PromptItem>) {
      if (!item.panelId) return;
      const index = this.items.findIndex(i => i.panelId === item.panelId);
      if (index !== -1) {
        this.items[index] = { ...this.items[index], ...item };
      }
    },
    
    // 根据 panelId 更新配置（因共用 panelId，无需额外关联）
    updateRandomConfigByPanelId(config: Partial<RandomConfig>) {
      if (!config.panelId) return;
      const index = this.randomConfigs.findIndex(c => c.panelId === config.panelId);
      if (index !== -1) {
        this.randomConfigs[index] = { ...this.randomConfigs[index], ...config };
      }
    },

    updateStateByType(data: Partial<PromptItem>) {
      // 确保传入数据包含类型和必要的标识信息
      if (!data.type) return;
      
      // 查找对应类型的项
      const itemsToUpdate = this.items.filter(item => item.type === data.type);
      
      if (itemsToUpdate.length > 0) {
        // 更新第一个找到的同类型项
        const firstItem = itemsToUpdate[0];
        this.updateItemByPanelId({
          panelId: firstItem.panelId,
          ...data
        });
      } else {
        // 如果没有对应类型的项，则创建新项并更新数据
        const newPanelId = this.addNewItem(data.type);
        // 使用nextTick确保新项已创建
        setTimeout(() => {
          this.updateItemByPanelId({
            panelId: newPanelId,
            ...data
          });
        }, 0);
      }
    },
    
    // 清空指定 panelId 的面板内容
    clearItemByPanelId(panelId: string) {
      this.updateItemByPanelId({
        panelId,
        name: '',
        customize_name: '',
        image: '',
        tags: '',
        rating: 0,
      });
    },
    
    // 添加新类型并创建实例
    addNewTypeWithInstance(type: string) {
      return this.addNewItem(type);
    },
    
    setRandomTag(tags: string) {
      this.random.tags = tags;
    },
    
    setCharacterTag(tags: string) {
      this.character.tags = tags;
    }
  }
});
    